package soundboard.player;

import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import soundboard.player.model.BoardFactory;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.AssetManager;
import android.media.AsyncPlayer;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class Player extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		/*
		try
		{
			BoardFactory.readBoard(this, getAssets().open("soundboard.brd"));
		}
		catch (IOException e)
		{
			throw new RuntimeException(e);
		}
		*/
		
		setVolumeControlStream(AudioManager.STREAM_MUSIC);

		setContentView(R.layout.main);

		Button button = (Button) findViewById(R.id.Button01);

		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				play2(new File("/sdcard/test.mp3"));
			}
		});

	}

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, 1, 0, "add Soundboard");
		menu.add(0, 2, 0, "What?");
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case 1:
			Toast.makeText(this, "creating new Soundboard", Toast.LENGTH_SHORT)
					.show();
			searchFile();
			break;
		case 2:
			Toast.makeText(this, "show about screen", Toast.LENGTH_SHORT)
					.show();
			break;
		}
		return false;
	}

	private void searchFile() {
		ProgressDialog dialog = ProgressDialog.show(Player.this, "",
				"Search Soundboard-Files", true);

		File directory = Environment.getExternalStorageDirectory();
		File[] files = directory.listFiles();
		boolean b = directory.canRead();

		if (files != null) {
			dialog.cancel();
		}
	}

	private SoundPool soundPool;
	private Map<File, Integer> soundPoolResources = new LinkedHashMap<File, Integer>();
	private Map<File, AsyncPlayer> asyncPlayerCache = new LinkedHashMap<File, AsyncPlayer>();

	private void play1(File file) {
		if (soundPool == null) {
			soundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
		}
		int soundId = soundPool.load(file.getPath(), 0);
		soundPoolResources.put(file, soundId);
		soundPool.play(soundId, 1.0f, 1.0f, 0, 0, 0.0f);
	}

	private void play2(File file) {
		AsyncPlayer asyncPlayer = asyncPlayerCache.get(file);
		Uri soundUri = Uri.fromFile(file);
		asyncPlayer = new AsyncPlayer("tag");
		asyncPlayer.play(getApplicationContext(), soundUri, false,
				AudioManager.STREAM_MUSIC);
	}
}